#!/bin/bash

# ================================================================
# TooBit监控系统 - 停止服务脚本
# ================================================================

PROJECT_ROOT="/Users/austin_w/PycharmProjects/toobit-monitor"
BACKEND_PID_FILE="${PROJECT_ROOT}/backend.pid"
FRONTEND_PID_FILE="${PROJECT_ROOT}/frontend.pid"

echo "🛑 停止TooBit监控系统..."

# 通过PID文件停止
if [ -f "$BACKEND_PID_FILE" ]; then
    BACKEND_PID=$(cat "$BACKEND_PID_FILE")
    if ps -p $BACKEND_PID > /dev/null 2>&1; then
        kill $BACKEND_PID
        echo "✅ 已停止后端服务 (PID: $BACKEND_PID)"
    fi
    rm -f "$BACKEND_PID_FILE"
fi

if [ -f "$FRONTEND_PID_FILE" ]; then
    FRONTEND_PID=$(cat "$FRONTEND_PID_FILE")
    if ps -p $FRONTEND_PID > /dev/null 2>&1; then
        kill $FRONTEND_PID
        echo "✅ 已停止前端服务 (PID: $FRONTEND_PID)"
    fi
    rm -f "$FRONTEND_PID_FILE"
fi

# 额外清理，确保所有相关进程都被停止
echo "🧹 清理残留进程..."
pkill -f "ruoyi-admin.jar" 2>/dev/null && echo "✅ 清理后端进程" || true
pkill -f "vue-cli-service serve" 2>/dev/null && echo "✅ 清理前端进程" || true

# 等待进程完全停止
sleep 2

# 检查端口是否已释放
echo "🔍 检查端口状态..."
if lsof -i :8080 >/dev/null 2>&1; then
    echo "⚠️  端口8080仍被占用:"
    lsof -i :8080
else
    echo "✅ 端口8080已释放"
fi

if lsof -i :1024 >/dev/null 2>&1; then
    echo "⚠️  端口1024仍被占用:"
    lsof -i :1024
else
    echo "✅ 端口1024已释放"
fi

echo ""
echo "🎯 停止完成!"
echo "📊 验证状态: ps aux | grep -E '(ruoyi-admin|vue-cli-service)'"
